<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .div1 {
            position: fixed;
            width: 100px;
            height: 100px;
            background-color: #f00;
        }
    </style>
</head>
<body>
    <div class="div1"></div>
</body>
<script>
    let div1 = document.querySelector(".div1");

    let x,y;
    // 拖动开关
    let flag = false;

    div1.addEventListener("mousedown",function(e) {
        let x = e.screenX;
        let y = e.screenY;
        flag = true;
    })

    function stopDrag() {
        flag = false;
    }

    div1.addEventListener("mouseup",stopDrag)
    div1.addEventListener("mouseout",stopDrag)

    div1.addEventListener("mousemove",function(e) {
        if (flag) {
            let moveX = e.screenX - x;
            let moveY = e.screenY - y;
            div1.style.left = div1.offsetLeft + moveX + "px"
            div1.style.top = div1.offsetTop + moveY + "px"
            x = e.screenX;
            y = e.screenY;
        }
    });
</script>
</html>